#include "frozen-bubble.h"

HashTable *imagetable = NULL;

FBImage *get_image (const char *file)
{
	FBImage *img = NULL;
	
	if (file)
	{
		if (!imagetable)
			imagetable = hashtable_new (1009, hashtable_str_hash, hashtable_str_compare, hashtable_str_duplicate);
		
		img = hashtable_find (imagetable, file);
	}
	
	if (!img)
	{
		char filename[100] = { 0 };
		SDL_Surface *surface = NULL;
		
		if (file)
		{
			strcat (filename, FPATH);
			strcat (filename, "gfx/");
			strcat (filename, file);
			
			if (!(surface = IMG_Load (filename)))
			{
				fprintf (logfile, "get_image: Unable to load image '%s'\n", file);
				exit (EXIT_FAILURE);
				return NULL;
			}
		}
		
		if (!(img = malloc (sizeof (FBImage))))
		{
			fprintf (logfile, "get_image: Unable to malloc FBImage for '%s'\n", file);
			exit (EXIT_FAILURE);
			return NULL;
		}
		
		img->surface = surface;
		img->rect.x = 0;
		img->rect.y = 0;
		
		if (surface)
		{
			img->rect.w = surface->w;
			img->rect.h = surface->h;
		}
		else
		{
			img->rect.w = 0;
			img->rect.h = 0;
		}
		
		if (file)
		{
			hashtable_insert (imagetable, file, img);
			
			#ifdef DEBUG
			fprintf (logfile, "get_image: Loaded image '%s'\n", file);
			#endif
		}
	}
	
	return img;
}

int get_image_list (const char *template, int start, int end, FBImage **images)
{
	for (int i = start; i <= end; i++)
	{
		char filename[50];
		FBImage *img;
		
		sprintf (filename, template, i);
		img = get_image (filename);
		
		if (images)
			images[i - start] = img;
	}
	
	return end - start + 1;
}

void put_image (FBImage *img, int x, int y)
{
	SDL_Rect drect;
	drect.x = x;
	drect.y = y;
	drect.w = img->surface->w;
	drect.h = img->surface->h;
	
	SDL_BlitSurface (img->surface, &img->rect, screen, &drect);
}

